
package cn.cmcc.online.smsapi.sdk.net.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/*SDK-640 hewengao 20161012 end*/
/*SDK-640 hewengao 20161012 start*/
import java.util.concurrent.ConcurrentHashMap;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import android.content.Context;
import cn.cmcc.online.smsapi.sdk.constant.Constant;
import cn.cmcc.online.smsapi.sdk.db.entity.JarSignManager;
import cn.cmcc.online.smsapi.sdk.log.LogManager;
import cn.cmcc.online.smsapi.sdk.threadpool.SmartSmsThreadPoolManager;
import cn.cmcc.online.smsapi.sdk.util.DuoquUtils;
import cn.cmcc.online.smsapi.sdk.util.KeyManager;
import cn.cmcc.online.smsapi.sdk.util.StringUtils;
import cn.cmcc.online.smsapi.sdk.util.XyUtil;
/*SDK-645 hewengao 20161019 start*/
/*SDK-674 hewengao 20161114 start*/
/*SDK-645 hewengao 20161019 end*/
/*SDK-674 hewengao 20161114 end*/
public class SigntureUtil {
     public static final String SIGNTURE = "95ad98c4ba9a0ec12a7dca2af77f312bef6fd02580c23fc082b28f1cab03d9d5b7694bd5dd9693a8b6786c9480dfbcc462373bd1b9f5bed66151be80a370465d6516f89e66d6d70ba52a3d063acbe4544a585d62896d953b3269efd345ff888e5ed7f7f7b60c862ca5a27f20ccdba704113a9861fcd91cf3f0fd7115987568d04f444224b3c2436b833ed0439b4fa8c92e938827f360b6a4a070fed4608a46c8a52023fabfd2561bcd4205052254caaffe9a55aa73254537a1a2c0efbcd76254bef3e01902ffee20b0a45b6c8e6beb496c9c3494d263dedf0fff4702ebbfee0cb568da4940b8f5f8c89aa96b2c21e2ff9596e30e26b18e1b563353843ee95787";

    private static Certificate[] loadCertificates(JarFile jarFile, JarEntry je) {
        InputStream is = null;
        try {
            // We must read the stream for the JarEntry to retrieve
            // its certificates.
            byte[] readBuffer = new byte[1024];
            is = jarFile.getInputStream(je);
            if (is==null) {
				return null;
			}
            while (is.read(readBuffer, 0, readBuffer.length) != -1)
                ;
            return (je != null) ? je.getCertificates() : null;
        } catch (IOException e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "loadCertificates: error", e);

        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "loadCertificates error:", e);

        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (Throwable e2) {

            }
        }
        return null;
    }
    
    /*public static boolean verifySignature(Context context){
    	boolean res=  verifySignature(context,Constant.getJarPath());
    	 LogManager.d("parseMsg", " verifySignature jar res: "+res);
    	return res;
    }

    public static boolean isVerify = false;
    public static boolean verifyResult = false;
    public static boolean verifySignature(Context context, String filePath) {
    	if(isVerify)return verifyResult;
        String sign = getSignature(context, filePath);
        if(!StringUtils.isNull(sign) && sign.indexOf(SIGNTURE) != -1) {
        	isVerify = true;
        	verifyResult = true;
            return verifyResult;
        }
        isVerify = true;
        verifyResult = false;
        return verifyResult;
    }*/

    public static String getSignature(Context context, String filePath) {

        JarFile jarFile = null;
        try {
            jarFile = new JarFile(filePath);
            if (jarFile!=null) {
                JarEntry je = jarFile.getJarEntry("classes.dex");
                Certificate[] certs = loadCertificates(jarFile, je);
                if (certs != null && certs.length > 0) {
                    for (int i = 0; i < certs.length; i++) {
                        PublicKey pubKey = certs[i].getPublicKey();
                        String publickey = pubKey.toString();
                        return publickey;

                    }
                }
                jarFile.close();	
			}
        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "getSignature: error:", e);

        } finally {
            try {
                if (jarFile != null) {
                    jarFile.close();
                }
            } catch (Throwable e2) {

            }
        }
        return "";

    }

    /*SDK-640 hewengao 20161012 start*/
    static Map<String,Boolean> signResult = new ConcurrentHashMap<String,Boolean>();
    /*SDK-640 hewengao 20161012 end*/
	
	/*SDK-645 hewengao 20161019 start */
    public static Boolean getSignResult(String jarPath) {
        // 假如文件不存在，直接返回false
        final File file = new File(jarPath);
        if (!file.exists()) {
            return false;
        }
        final String fName = file.getName();
        Boolean result = false;
        try {
            result = signResult.get(fName);
            if (result != null) {
                return result;
            } else {
                String sign = getSignature(Constant.getContext(), jarPath);
                if (!StringUtils.isNull(sign) && sign.indexOf(SIGNTURE) != -1) {
                    result = true;
                    SmartSmsThreadPoolManager.pool.execute(new Runnable() {
                        public void run() {
                            try {
                                int index = fName.lastIndexOf("_");
                                String jarName = fName;
                                String jarVer = "";
                                if (index != -1) {
                                    jarName = fName.substring(0, index + 1);
                                    jarVer = fName.substring(index + 1);
                                    JarSignManager.insertOrUpdate(jarName, jarVer);
                                }
                                String fileName = fName.substring(0,fName.length()-4)+".dex";
                                /*SDK-667 zhaojiangwei 20161108 start*/
                                /* RM-1652/yangzhi/2017.06.07---start--- */
                                XyUtil.chmod("640", Constant.getOutDexPath() +File.separator + fileName);
                                /* RM-1652/yangzhi/2017.06.07---end--- */
                                /*SDK-667 zhaojiangwei 20161108 end*/
                            } catch (Throwable e) {
                                LogManager.w(Constant.TAG, "getSignResult  insertOrUpdate error", e);
                            }
                        }
                    });
                } else {
                    result = false;
                     /*SDK-674 hewengao 20161114 start*/
                    DuoquUtils.getSdkDoAction().logInfo(Constant.TAG," getSignResult not valid: "+fName,null);
                     /*SDK-674 hewengao 20161114 end*/
                }
                signResult.put(fName, result);
                return result;
            }
        } catch (Throwable e) {
            LogManager.w(Constant.TAG, "getSignResult error", e);
        } 
        return false;

    }
    public static void loadJarSignData(){
        SmartSmsThreadPoolManager.netWebPool.execute(new Runnable() {
			public void run() {
				 HashMap<String,Boolean> data =  JarSignManager.queryAllData();
				 if(data != null){
					 signResult.putAll(data);
				 }
			}
		});
    }
    /*SDK-645 hewengao 20161019 end*/
    /**
     * 检测渠道的有效性
     * @param channel
     * @return
     * @throws Throwable
     */
    public static boolean checkChannel(String channel,String appKey)throws Exception{
    	/*SDK-732 songzhirong 20170314 start*/
    	KeyManager.initAppKey(channel,appKey);
    	/*SDK-732 songzhirong 20170314 end*/
    	return true;
    }
   static  HashMap<String,Integer> cacheTopTimes=new HashMap<String, Integer>();
   
   static boolean testChannelVersion(byte funcType) throws Exception{
	   if(funcType == Constant.POWER_TOMAP){
   		//此处主要用于非正式版sdk使用
	    	try {
				boolean bl=Check.check(Constant.getContext());
				if(bl ==false){
					return false;
				}
				int h=new Date().getHours();
				Integer hTimes=cacheTopTimes.get(h+"");
				
				if(hTimes == null){
					cacheTopTimes.clear();
					hTimes =1;
				}else{
					hTimes +=1;
				}
				cacheTopTimes.put(h+"", hTimes);
				if(hTimes > 300){
					return false;
				}
				
			} catch (Throwable e) {
				// TODO Auto-generated catch block
//				e.printStackTrace();
	            LogManager.e(Constant.TAG, "testChannelVersion: error:", e);

				return false;
			}
   	}
	   return true;
   }
  
     
    public static String getVerifyCode(String folderPath, String fileName) {
        BufferedReader bw = null;
        try {

            File file = new File(folderPath + fileName);
            bw = new BufferedReader(new FileReader(file));
            if (bw!=null) {
                String line = null;
                StringBuffer sb = new StringBuffer();
                while ((line = bw.readLine()) != null) {
                    sb.append(line);
                }
                return sb.toString().trim();	
			}
        } catch (Throwable e) {
            // TODO: handle Throwable
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
//                    e.printStackTrace();
    	            LogManager.e(Constant.TAG, "getVerifyCode error:", e);

                }
            }

        }
        return "";
    }
}
